package com.laizhenghua.wxstub.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.laizhenghua.wxstub.constant.AppConstant;
import com.laizhenghua.wxstub.dto.WxUserDTO;
import com.laizhenghua.wxstub.entiry.LoginUser;
import com.laizhenghua.wxstub.service.LoginService;
import com.laizhenghua.wxstub.utils.JwtUtil;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: laizhenghua
 * @date: 2022/9/8 20:28
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {
    private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LoginServiceImpl.class);
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private CacheManager cacheManager;

    @Override
    public String login(String loginId, String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginId, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate == null) {
            return null;
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        if (loginUser.getUser() == null) {
            return null;
        }
        // mongodb主键
        String _id = loginUser.getUser().get_id();
        String token = JwtUtil.createToken(null, _id, null);
        // token缓存(有效期1h)
        Cache cache = cacheManager.getCache(AppConstant.LOGIN_TOKEN_CACHE_NAME);
        Element element = new Element(_id, loginUser);
        cache.put(element);
        log.info(String.format("put ehcache(key=%s)", _id));
        return token;
    }
}
